package wang.aweb.childcar.controller.api;

import cn.felord.payment.wechat.v3.WechatApiProvider;
import cn.felord.payment.wechat.v3.WechatResponseEntity;
import cn.felord.payment.wechat.v3.model.*;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jodd.util.Consumers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import wang.aweb.childcar.common.ApiRestResponse;
import wang.aweb.childcar.filter.UserFilter;
import wang.aweb.childcar.model.pojo.Member;
import wang.aweb.childcar.model.pojo.MoneyMeal;
import wang.aweb.childcar.service.CzOrderService;
import wang.aweb.childcar.service.MemberService;
import wang.aweb.childcar.service.MoneyMealService;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.function.Consumer;

@RestController
public class PayController {
    @Autowired
    private CzOrderService czOrderService;
    @Autowired
    private MoneyMealService moneyMealService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private WechatApiProvider wechatApiProvider;
    @PostMapping("/api/wechat/doPay")
    public ApiRestResponse doPay(@RequestBody Map<String,Integer> reqMap){
        Integer mealId=reqMap.get("mealId");
        MoneyMeal moneyMeal=moneyMealService.findById(mealId);
        Member member=memberService.selectById(UserFilter.memberThreadLocal.get().getId());
        String orderno=czOrderService.add(moneyMeal,member);

        PayParams payParams=new PayParams();
        Amount amount=new Amount();
        amount.setCurrency("CNY");
        amount.setTotal(moneyMeal.getPrice());
        payParams.setAmount(amount);
        payParams.setDescription("用户充值");
        Payer payer=new Payer();
        payer.setOpenid(member.getOpenid());
        payParams.setPayer(payer);
        payParams.setNotifyUrl("/wechat/callback");
        payParams.setOutTradeNo(orderno);
        WechatResponseEntity<ObjectNode> responseEntity=wechatApiProvider.directPayApi("miniapp").jsPay(payParams);
        ObjectNode objectNode=responseEntity.getBody();
        return ApiRestResponse.success(objectNode);
    }
    @PostMapping("/wechat/callback")
    public ApiRestResponse callback(HttpServletRequest req){
        ResponseSignVerifyParams rsvps=new ResponseSignVerifyParams();
        rsvps.setWechatpayNonce(req.getHeader("Wechatpay-Nonce"));
        rsvps.setWechatpaySerial(req.getHeader("Wechatpay-Serial"));
        rsvps.setWechatpaySignature(req.getHeader("Wechatpay-Signature"));
        rsvps.setWechatpayTimestamp(req.getHeader("Wechatpay-Timestamp"));
        String body="";
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()))) {
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            body = stringBuilder.toString();

        } catch (Exception e){
            e.printStackTrace();
        }
        rsvps.setBody(body);

        System.out.println(rsvps.toString());
        Map res= wechatApiProvider.callback("miniapp").transactionCallback(rsvps,(TransactionConsumeData t)->{
                    System.out.println("接收到的参数："+t.toString());
            System.out.println("订单号为："+t.getOutTradeNo());
                    if(t.getTradeState().toString()=="SUCCESS"){
                        String orderNo=t.getOutTradeNo();
                        czOrderService.pay(orderNo);
                    }

        });
        System.out.println(res);

        return ApiRestResponse.success(res);
    }
}
